#include "tcpserver.h"
#include <QString>
#include <QThread>

TCPServer::TCPServer(QObject *parent) : QObject(parent)
{
    client_nums = 0;
    client_max_nums = 5;
    threadpool = new ThreadPool(client_max_nums);
    m_server = new QTcpServer(this);
    m_server->moveToThread(QThread::currentThread());//服务器对象一直在主线程
}

TCPServer::~TCPServer()
{
    closeServer();
    delete threadpool;
}

void TCPServer::openServer()
{
    if(m_server->listen(QHostAddress::Any, 8090))
    {
        qDebug()<<"服务器开始监听";
        connect(m_server, &QTcpServer::newConnection, this, &TCPServer::onNewConnection);
        emit sendServerState(true);
    }
    else
    {
        qDebug()<<"服务器开启失败";
        emit sendServerState(false);
    }

}

void TCPServer::closeServer()
{

    //关闭所有客户端再关闭服务器
    QMutexLocker locker(&m_clientsMutex);
    foreach (QTcpSocket *client, m_clients) {
        client->disconnectFromHost();
        client->deleteLater();
    }
    m_clients.clear();
    client_nums = 0;
    emit changeClientNum(client_nums);

    m_server->close();
    qDebug()<<"服务器关闭";
    emit sendServerState(false);
}

void TCPServer::onNewConnection()
{
    QTcpSocket *client = m_server->nextPendingConnection(); //得到尝试连接的客户端的套接字

    if(client_nums >= 5)
    {
        qDebug()<<"线程池已满";
        client->disconnectFromHost(); // 如果超出最大连接数，拒绝连接
        client->deleteLater();
        return ;
    }

    // 将新客户端添加到列表
    {
        QMutexLocker locker(&m_clientsMutex);
        m_clients.append(client);
        client_nums++;
    }
    emit changeClientNum(client_nums);
    QString rename = "用户" + QString::number(client_nums);//给客户端命名
    clientRename(client, rename);
    // 使用线程池处理数据
    connect(client, &QTcpSocket::readyRead, this, [this, client](){//客户端
        threadpool->enqueue([this, client](){
            QString message = QString::fromUtf8(client->readAll());
            QMetaObject::invokeMethod(this, "showChatMessage",
                                    Qt::QueuedConnection,
                                    Q_ARG(QString, message));
        });}, Qt::DirectConnection);

    connect(client, &QTcpSocket::disconnected, this, [this, client]() {//客户端断开链接触发
            qDebug() << "客户端断开信号触发";
            onClientDisconnected();});

}

void TCPServer::onClientDisconnected()
{   
    QTcpSocket *client = qobject_cast<QTcpSocket*>(sender());
    if (!client) return;
    qDebug() << "客户端断开:" << client->peerAddress().toString();

    {
        QMutexLocker locker(&m_clientsMutex);
        if (m_clients.removeOne(client)) {
            client_nums--;
            emit changeClientNum(client_nums);
        }
    }

    client->deleteLater();
}

void TCPServer::clientRename(QTcpSocket *client, QString rename)
{
    if (client && client->state() == QTcpSocket::ConnectedState)
    {
        client->write(rename.toUtf8() + "\n");
    }
}











